/**
 * 视频API封装模块
 * @author HalRui
 * @version 1.0.0
 * @description 封装视频相关的数据库操作API，提供视频发布、列表、详情、搜索等功能
 * @date 2025年9月28日
 */

const videosModel = require('../models/videos-model');
const userinfosModel = require('../models/userinfos-model');
const connectionPool = require('../utils/connection-pool');

/**
 * 确保数据库连接
 * @returns {Object} 连接状态
 */
function ensureConnection() {
    const status = connectionPool.getConnectionStatus();
    if (!status.mongodb.connected) {
        return {
            success: false,
            message: 'MongoDB 未连接'
        };
    }
    return { success: true };
}

module.exports = {
    /**
     * 发布视频
     * @param {Object} videoData - 视频数据
     * @returns {Object} 发布结果
     */
    publishVideo: async function(videoData) {
        const connectionCheck = ensureConnection();
        if (!connectionCheck.success) {
            return connectionCheck;
        }

        const result = await videosModel.createVideo(videoData);
        if (result.success) {
            return {
                success: true,
                message: result.video.getSafeJSON()
            }
        } else {
            return {
                success: false,
                message: result.error
            }
        }
    },

    /**
     * 获取视频列表
     * @param {Object} options - 查询选项
     * @param {number} options.page - 页码
     * @param {number} options.limit - 每页数量
     * @param {string} options.sortBy - 排序字段
     * @param {string} options.sortOrder - 排序方向
     * @param {number} options.fromID - 用户ID（可选）
     * @param {string} options.videoType - 视频类型（可选）
     * @returns {Object} 视频列表
     */
    getVideoList: async function(options = {}) {
        const connectionCheck = ensureConnection();
        if (!connectionCheck.success) {
            return connectionCheck;
        }

        try {
            const {
                page = 1,
                limit = 20,
                sortBy = 'publishTime',
                sortOrder = 'desc',
                fromID,
                videoType,
                isPrivate = false
            } = options;

            // 构建查询条件
            const query = { isPrivate };
            if (fromID) query.fromID = fromID;
            if (videoType) query.videoType = videoType;

            // 构建排序条件
            const sort = {};
            sort[sortBy] = sortOrder === 'desc' ? -1 : 1;

            const skip = (page - 1) * limit;

            const videos = await videosModel.find(query)
                .sort(sort)
                .skip(skip)
                .limit(limit)
                .lean();

            const total = await videosModel.countDocuments(query);

            // 获取用户信息

            const videosWithUserInfo = await Promise.all(
                videos.map(async (video) => {
                    const user = await userinfosModel.findOne({ userId: video.fromID });
                    return {
                        ...video,
                        userInfo: user ? {
                            userId: user.userId,
                            username: user.username,
                            nickname: user.nickname,
                            avatar: user.avatar
                        } : null
                    };
                })
            );

            return {
                success: true,
                videos: videosWithUserInfo,
                pagination: {
                    page,
                    limit,
                    total,
                    pages: Math.ceil(total / limit)
                }
            };
        } catch (error) {
            return {
                success: false,
                message: '获取视频列表失败：' + error.message
            };
        }
    },

    /**
     * 获取视频详情
     * @param {number} videoID - 视频ID
     * @param {number} viewerID - 观看者ID（可选，用于增加观看次数）
     * @returns {Object} 视频详情
     */
    getVideoDetail: async function(videoID, viewerID = null) {
        const connectionCheck = ensureConnection();
        if (!connectionCheck.success) {
            return connectionCheck;
        }

        try {
            const video = await videosModel.findOne({ videoID });
            if (!video) {
                return {
                    success: false,
                    message: '视频不存在'
                };
            }

            // 增加观看次数（如果提供了观看者ID且不是视频作者）
            if (viewerID && viewerID !== video.fromID) {
                await videosModel.updateOne(
                    { videoID },
                    { $inc: { viewCount: 1 } }
                );
                video.viewCount += 1;
            }

            // 获取用户信息
            const user = await userinfosModel.findOne({ userId: video.fromID });

            return {
                success: true,
                video: {
                    ...video.toObject(),
                    userInfo: user ? {
                        userId: user.userId,
                        username: user.username,
                        nickname: user.nickname,
                        avatar: user.avatar,
                        userLevel: user.userLevel
                    } : null
                }
            };
        } catch (error) {
            return {
                success: false,
                message: '获取视频详情失败：' + error.message
            };
        }
    },

    /**
     * 搜索视频
     * @param {Object} searchOptions - 搜索选项
     * @param {string} searchOptions.keyword - 搜索关键词
     * @param {number} searchOptions.page - 页码
     * @param {number} searchOptions.limit - 每页数量
     * @param {string} searchOptions.sortBy - 排序字段
     * @param {string} searchOptions.sortOrder - 排序方向
     * @returns {Object} 搜索结果
     */
    searchVideos: async function(searchOptions = {}) {
        const connectionCheck = ensureConnection();
        if (!connectionCheck.success) {
            return connectionCheck;
        }

        try {
            const {
                keyword,
                page = 1,
                limit = 20,
                sortBy = 'publishTime',
                sortOrder = 'desc'
            } = searchOptions;

            if (!keyword) {
                return {
                    success: false,
                    message: '搜索关键词不能为空'
                };
            }

            // 构建搜索条件
            const query = {
                isPrivate: false,
                $or: [
                    { title: { $regex: keyword, $options: 'i' } },
                    { content: { $regex: keyword, $options: 'i' } }
                ]
            };

            // 构建排序条件
            const sort = {};
            sort[sortBy] = sortOrder === 'desc' ? -1 : 1;

            const skip = (page - 1) * limit;

            const videos = await videosModel.find(query)
                .sort(sort)
                .skip(skip)
                .limit(limit)
                .lean();

            const total = await videosModel.countDocuments(query);

            // 过滤掉无效日期的视频和时间范围外的视频
            const validVideos = videos.filter(video => {
                if (!video.publishTime || 
                    !(video.publishTime instanceof Date) || 
                    isNaN(video.publishTime.getTime())) {
                    return false;
                }
                // 检查是否在时间范围内
                return video.publishTime >= startDate;
            });

            const videosWithUserInfo = await Promise.all(
                validVideos.map(async (video) => {
                    const user = await userinfosModel.findOne({ userId: video.fromID });
                    return {
                        ...video,
                        userInfo: user ? {
                            userId: user.userId,
                            username: user.username,
                            nickname: user.nickname,
                            avatar: user.avatar
                        } : null
                    };
                })
            );

            return {
                success: true,
                videos: videosWithUserInfo,
                pagination: {
                    page,
                    limit,
                    total,
                    pages: Math.ceil(total / limit)
                },
                keyword
            };
        } catch (error) {
            return {
                success: false,
                message: '搜索视频失败：' + error.message
            };
        }
    },

    /**
     * 更新视频信息
     * @param {number} videoID - 视频ID
     * @param {number} userID - 用户ID
     * @param {Object} updateData - 更新数据
     * @returns {Object} 更新结果
     */
    updateVideo: async function(videoID, userID, updateData) {
        const connectionCheck = ensureConnection();
        if (!connectionCheck.success) {
            return connectionCheck;
        }

        try {
            const video = await videosModel.findOne({ videoID });
            if (!video) {
                return {
                    success: false,
                    message: '视频不存在'
                };
            }

            // 检查权限
            if (video.fromID !== userID) {
                return {
                    success: false,
                    message: '无权限修改此视频'
                };
            }

            // 允许更新的字段
            const allowedFields = ['title', 'content', 'isPrivate', 'isFeatured'];
            const filteredData = {};
            
            Object.keys(updateData).forEach(key => {
                if (allowedFields.includes(key)) {
                    filteredData[key] = updateData[key];
                }
            });

            if (Object.keys(filteredData).length === 0) {
                return {
                    success: false,
                    message: '没有有效的更新字段'
                };
            }

            filteredData.updatedAt = new Date();

            const updatedVideo = await videosModel.findOneAndUpdate(
                { videoID },
                filteredData,
                { new: true }
            );

            return {
                success: true,
                video: updatedVideo.getSafeJSON()
            };
        } catch (error) {
            return {
                success: false,
                message: '更新视频失败：' + error.message
            };
        }
    },

    /**
     * 删除视频
     * @param {number} videoID - 视频ID
     * @param {number} userID - 用户ID
     * @returns {Object} 删除结果
     */
    deleteVideo: async function(videoID, userID) {
        const connectionCheck = ensureConnection();
        if (!connectionCheck.success) {
            return connectionCheck;
        }

        try {
            const video = await videosModel.findOne({ videoID });
            if (!video) {
                return {
                    success: false,
                    message: '视频不存在'
                };
            }

            // 检查权限
            if (video.fromID !== userID) {
                return {
                    success: false,
                    message: '无权限删除此视频'
                };
            }

            await videosModel.deleteOne({ videoID });

            return {
                success: true,
                message: '视频删除成功'
            };
        } catch (error) {
            return {
                success: false,
                message: '删除视频失败：' + error.message
            };
        }
    },

    /**
     * 获取热门视频
     * @param {Object} options - 选项
     * @param {number} options.limit - 限制数量
     * @param {number} options.timeRange - 时间范围（天数）
     * @returns {Object} 热门视频列表
     */
    getPopularVideos: async function(options = {}) {
        const connectionCheck = ensureConnection();
        if (!connectionCheck.success) {
            return connectionCheck;
        }

        try {
            const { limit = 20, timeRange = 7 } = options;
            
            const startDate = new Date();
            startDate.setDate(startDate.getDate() - timeRange);

            const videos = await videosModel.find({
                isPrivate: false
            })
            .sort({ 
                likeCount: -1, 
                viewCount: -1, 
                publishTime: -1 
            })
            .limit(limit)
            .lean();

            // 过滤掉无效日期的视频和时间范围外的视频
            const validVideos = videos.filter(video => {
                if (!video.publishTime || 
                    !(video.publishTime instanceof Date) || 
                    isNaN(video.publishTime.getTime())) {
                    return false;
                }
                // 检查是否在时间范围内
                return video.publishTime >= startDate;
            });

            const videosWithUserInfo = await Promise.all(
                validVideos.map(async (video) => {
                    const user = await userinfosModel.findOne({ userId: video.fromID });
                    return {
                        ...video,
                        userInfo: user ? {
                            userId: user.userId,
                            username: user.username,
                            nickname: user.nickname,
                            avatar: user.avatar
                        } : null
                    };
                })
            );

            return {
                success: true,
                videos: videosWithUserInfo
            };
        } catch (error) {
            return {
                success: false,
                message: '获取热门视频失败：' + error.message
            };
        }
    },

    /**
     * 获取用户的视频列表
     * @param {number} userID - 用户ID
     * @param {Object} options - 选项
     * @returns {Object} 用户视频列表
     */
    getUserVideos: async function(userID, options = {}) {
        const connectionCheck = ensureConnection();
        if (!connectionCheck.success) {
            return connectionCheck;
        }

        try {
            const {
                page = 1,
                limit = 20,
                includePrivate = false,
                viewerID = null
            } = options;

            // 构建查询条件
            const query = { fromID: userID };
            
            // 如果不是视频作者本人，则不显示私有视频
            if (!includePrivate || viewerID !== userID) {
                query.isPrivate = false;
            }

            const skip = (page - 1) * limit;

            const videos = await videosModel.find(query)
                .sort({ publishTime: -1 })
                .skip(skip)
                .limit(limit)
                .lean();

            const total = await videosModel.countDocuments(query);

            // 获取用户信息
            const user = await userinfosModel.findOne({ userId: userID });

            return {
                success: true,
                videos,
                userInfo: user ? {
                    userId: user.userId,
                    username: user.username,
                    nickname: user.nickname,
                    avatar: user.avatar,
                    userLevel: user.userLevel
                } : null,
                pagination: {
                    page,
                    limit,
                    total,
                    pages: Math.ceil(total / limit)
                }
            };
        } catch (error) {
            return {
                success: false,
                message: '获取用户视频失败：' + error.message
            };
        }
    }
}